package com.definesys.smecrailtransit.module.TotalTime;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.adapter.LineStationAdapter.LineStationAdapter;
import com.definesys.smecrailtransit.adapter.SelctLineAdapter.SelectLineAdapter;
import com.definesys.smecrailtransit.adapter.SelectMonthAdapter.SelectMonthAdapter;
import com.definesys.smecrailtransit.adapter.SelectUserAdapter.SelectUserAdapter;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentTotalTimeBinding;


import com.definesys.smecrailtransit.module.TotalTime.ViewController.ViewController;
import com.definesys.smecrailtransit.module.TotalTime.bean.TotalTimeBean;
import com.definesys.smecrailtransit.module.TotalTime.dialog.TotalTimeDialog;
import com.definesys.smecrailtransit.utils.ToastyUtils;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;

/**
 * Created by cjy on 2017/8/14.
 */

public class TotalTimeFragment extends SmecBaseFragment<TotalTimePresenter> {

    //RxJava,组件间通讯的静态常量
    public static final String CLOSE_DIALOG_BACKGROUND = "closeDialogBackground(Object o)";
    public static final String CHANGE_MONTH = "changeMonthTotalTime(Object o)";
    public static final String CHANGE_USER = "changeUserTotalTime(Object o)";
    public static final String CHANGE_LINE = "changeLineTotalTime(Object o)";
    public static final String GET_TOTAL_TIME_SUCCESS = "getTotalTimeSuccess(Object o)";
    public static final String GET_TOTAL_TIME_FAILED = "getTotalTimeFailed(Object o)";
    public static final String LOAD = "load(Object o)";
    public static final String JPUSH_LOAD_RUN_TIME = "jpushLoadRunTime(Object o)";
    public static final String SHOW_STATION_TIME = "showStationTime(Object o)";

    private FragmentTotalTimeBinding fragmentTotalTimeBinding;

    private LineStationAdapter lineStationAdapter1;
    private LineStationAdapter lineStationAdapter2;
    private SelectMonthAdapter selectMonthAdapter;
    private SelectUserAdapter selectUserAdapter;
    private SelectLineAdapter selectLineAdapter;
    private DisplayMetrics dm;
    private ViewController viewController;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentTotalTimeBinding= DataBindingUtil.inflate(inflater, R.layout.fragment_total_time,container,false);
        viewController = new ViewController(fragmentTotalTimeBinding,getPersenter());
        dm = getResources().getDisplayMetrics();
        _initView();
        return fragmentTotalTimeBinding.getRoot();
    }

    private void _initView(){

        //设置下拉刷新的属性
        fragmentTotalTimeBinding.refreshLayout.setHeaderView(SmecRailConstant.getSinaRefreshView());
        fragmentTotalTimeBinding.refreshLayout.setAutoLoadMore(true);
        fragmentTotalTimeBinding.refreshLayout.setEnableOverScroll(false);
        fragmentTotalTimeBinding.refreshLayout.setEnableLoadmore(false);
        fragmentTotalTimeBinding.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                viewController.getNetWorkData();
            }
        });


        //设置线路数据
        viewController.getLineList().add("12号线");
        viewController.getLineList().add("1号线");
        viewController.getLineList().add("2号线");
        viewController.getLineList().add("3号线");
        viewController.getLineList().add("4号线");
        viewController.getLineList().add("5号线");
        viewController.getLineList().add("9号线");
        viewController.getLineList().add("16号线");


        //设置界面显示的数据
        int l=viewController.getSelectLine()!=null ? viewController.getSelectLine().length()-2:0;
        fragmentTotalTimeBinding.nowLine.setText(viewController.getSelectLine().substring(0,l));
        fragmentTotalTimeBinding.nowUser.setText(viewController.getSelectUser());
        fragmentTotalTimeBinding.startDate.setText(viewController.getStartDate());
        fragmentTotalTimeBinding.endDate.setText(viewController.getEndDate());


        //设置界面的Adapter
        lineStationAdapter1 = new LineStationAdapter(dm,this.mRxBus,SmecRailApi.MonthCode.TOTALTIME,getContext());
        lineStationAdapter2 = new LineStationAdapter(dm,this.mRxBus,SmecRailApi.MonthCode.TOTALTIME,getContext());

        selectUserAdapter = new SelectUserAdapter(this.mRxBus, SmecRailApi.MonthCode.TOTALTIME);
        selectLineAdapter = new SelectLineAdapter(viewController.getLineList(),this.mRxBus,SmecRailApi.MonthCode.TOTALTIME);

        viewController.setSelectLineAdapter(selectLineAdapter);
        viewController.setSelectMonthAdapter(selectMonthAdapter);
        viewController.setSelectUserAdapter(selectUserAdapter);

        //选择运营商下拉框
        fragmentTotalTimeBinding.selectUser.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentTotalTimeBinding.selectUser.setAdapter(selectUserAdapter);
        //选择线路下拉框
        fragmentTotalTimeBinding.selectLine.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentTotalTimeBinding.selectLine.setAdapter(selectLineAdapter);

        //界面图标
        fragmentTotalTimeBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
        fragmentTotalTimeBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
    }

    public static TotalTimeFragment newInstance() {
        Bundle args = new Bundle();
        TotalTimeFragment fragment = new TotalTimeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected TotalTimePresenter getPersenter() {
        return new TotalTimePresenter(getActivity());
    }

    /**
     * 从导航栏进入改Fragment 时 应该只让第一个Fragment刷新数据
     * @param position
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void intFragment(String position){
        if(position.equals("4")){
            fragmentTotalTimeBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentTotalTimeBinding.refreshLayout.startRefresh();
                }
            },200);
        }
    }

    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOAD)
            }
    )
    public void load(Object o){
        this.viewController.getNetWorkData();
    }

    /**
     * 当从推送点击跳转到该页面时
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(JPUSH_LOAD_RUN_TIME)
            }
    )
    public void jpushLoad(HashMap<String,String> hashMap){
        fragmentTotalTimeBinding.calendar.clearSelection();
        if(hashMap.get("from") == null || hashMap.get("from").equals("") || hashMap.get("to") == null || hashMap.get("to").equals("")){
            //this.viewController.getNetWorkData();
        }else{
            this.viewController.setStartDate(hashMap.get("from"));
            this.viewController.setEndDate(hashMap.get("to"));
            this.viewController.getNetWorkData();
            fragmentTotalTimeBinding.startDate.setText(hashMap.get("from"));
            fragmentTotalTimeBinding.endDate.setText(hashMap.get("to"));
        }
    }


    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CLOSE_DIALOG_BACKGROUND)
            }
    )
    public void closeDialogBackground(Object o){
        this.fragmentTotalTimeBinding.choice.setVisibility(View.GONE);
        this.fragmentTotalTimeBinding.pull.setVisibility(View.GONE);
        this.fragmentTotalTimeBinding.line.setVisibility(View.GONE);
    }

    /**
     * 当切换运营商时
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_USER)
            }
    )
    public void changeUser(Object o){
        this.fragmentTotalTimeBinding.pull.setVisibility(View.GONE);
        this.fragmentTotalTimeBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);

        viewController.setSelectUser(String.valueOf(o));
        fragmentTotalTimeBinding.nowUser.setText(viewController.getSelectUser());

        viewController.getNetWorkData();
    }

    /**
     * 当切换线路时
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_LINE)
            }
    )
    public void changeLine(Object o){
        if((boolean)o){
            ToastyUtils.showWaringToast(this.fragmentTotalTimeBinding.getRoot().getContext(),
                    "当前版本只有12号线的数据");
        }
        this.fragmentTotalTimeBinding.line.setVisibility(View.GONE);
        this.fragmentTotalTimeBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
    }

    /**
     * 获取页面数据成功
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_TOTAL_TIME_SUCCESS)
            }
    )
    public void getTotalTimeSuccess(TotalTimeBean o){
        viewController.getLocalData(o);

        if(o.getLine().get(0).getAbnormalCount() != 0){
            fragmentTotalTimeBinding.hint.setVisibility(View.VISIBLE);
        }else{
            fragmentTotalTimeBinding.hint.setVisibility(View.GONE);
        }
        fragmentTotalTimeBinding.hint.setText("红色站点表示该站点"+viewController.getStartDate()+"至"+viewController.getEndDate()+"处于非正常状态");

        changeView();
        fragmentTotalTimeBinding.refreshLayout.finishRefreshing();
    }

    /**
     * 获取页面数据失败
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_TOTAL_TIME_FAILED)
            }
    )
    public void getTotalTimeFailed(Object o){
        ToastyUtils.showErrorToast(fragmentTotalTimeBinding.getRoot().getContext(),"当前数据为旧数据，网络良好后请刷新");
        fragmentTotalTimeBinding.refreshLayout.finishRefreshing();
    }

    /**
     * 展示站点运行时长弹出框
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(SHOW_STATION_TIME)
            }
    )
    public void showStationTime(HashMap<String,Object> o){
        TotalTimeDialog totalTimeDialog = new TotalTimeDialog(this.getContext(),R.style.project_back,
                viewController.getStartDate(),viewController.getEndDate(),o);
        totalTimeDialog.setTotalTimeDialog(totalTimeDialog);
        totalTimeDialog.show();
    }

    //处理根据获取的数据，跟新页面
    private void changeView(){
        //设置运营商下拉列表
        if(viewController.getUserList() != null & viewController.getUserList().size() != 0){
            selectUserAdapter.setList(viewController.getUserList());
        }
        selectUserAdapter.notifyDataSetChanged();

        //设置站点显示数据
        if(lineStationAdapter1.getList() == null || lineStationAdapter1.getList().size() == 0){
            if(viewController.getList() != null & viewController.getList().size() != 0){
                lineStationAdapter1.setList(viewController.getList());
                lineStationAdapter1.showAnimation = true;
            }
            fragmentTotalTimeBinding.invalidateAll();

            fragmentTotalTimeBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineStationAdapter1.showAnimation = false;
                }
            },500);

            fragmentTotalTimeBinding.recyclerView.setItemAnimator(new SlideInLeftAnimator());
            fragmentTotalTimeBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            fragmentTotalTimeBinding.recyclerView.setAdapter(lineStationAdapter1);

            lineStationAdapter2.setList(new ArrayList<>());
        }else{
            if(viewController.getList() != null & viewController.getList().size() != 0){
                lineStationAdapter2.setList(viewController.getList());
                lineStationAdapter2.showAnimation = true;
            }
            lineStationAdapter2.notifyDataSetChanged();
            fragmentTotalTimeBinding.invalidateAll();

            fragmentTotalTimeBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lineStationAdapter2.showAnimation = false;
                }
            },500);

            fragmentTotalTimeBinding.recyclerView.setItemAnimator(new SlideInLeftAnimator());
            fragmentTotalTimeBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            fragmentTotalTimeBinding.recyclerView.setAdapter(lineStationAdapter2);

            lineStationAdapter1.setList(new ArrayList<>());
        }
    }
}
